import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    specialRequests: ''
  }),
  
  getters: {
    itemCount: (state) => state.items.reduce((count, item) => count + item.quantity, 0),
    totalPoints: (state) => state.items.reduce((sum, item) => sum + (item.points * item.quantity), 0),
    isEmpty: (state) => state.items.length === 0
  },
  
  actions: {
    addToCart(dish) {
      const existingItem = this.items.find(item => item.id === dish.id)
      if (existingItem) {
        existingItem.quantity += 1
      } else {
        this.items.push({
          ...dish,
          quantity: 1
        })
      }
    },
    
    removeFromCart(dishId) {
      const index = this.items.findIndex(item => item.id === dishId)
      if (index > -1) {
        this.items.splice(index, 1)
      }
    },
    
    updateQuantity(dishId, quantity) {
      const item = this.items.find(item => item.id === dishId)
      if (item) {
        if (quantity <= 0) {
          this.removeFromCart(dishId)
        } else {
          item.quantity = quantity
        }
      }
    },
    
    incrementQuantity(dishId) {
      const item = this.items.find(item => item.id === dishId)
      if (item) {
        item.quantity += 1
      }
    },
    
    decrementQuantity(dishId) {
      const item = this.items.find(item => item.id === dishId)
      if (item && item.quantity > 1) {
        item.quantity -= 1
      } else {
        this.removeFromCart(dishId)
      }
    },
    
    clearCart() {
      this.items = []
      this.specialRequests = ''
    },
    
    setSpecialRequests(requests) {
      this.specialRequests = requests
    },
    
    getCartItems() {
      return this.items
    }
  },
  
  persist: {
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
    }
  }
})